<?php

namespace app\meizhuangapi\model;

use app\meizhuangapi\model\User as UserModel;
use app\meizhuangapi\model\UserCoupon as UserCouponModel;
use app\meizhuangapi\service\order\PaySuccess;
use app\common\enum\order\Status as OrderStatusEnum;
use app\common\enum\order\PayType as PayTypeEnum;
use app\meizhuangapi\service\Payment as PaymentService;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\service\goods\source\Factory as FactoryStock;
use app\common\exception\BaseException;
use think\Db;
use app\meizhuangapi\model\OrderGoods as orderGoodsModel;

use app\api\model\Order as OedernModel;

/**
 * 订单模型
 * Class Order
 * @package app\api\model
 */
class Order extends OedernModel
{
    /**
     * 用户中心订单列表
     * @param $user_id
     * @param string $type
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id, $type = 'all',$goods_name){
        //根据产品名称获取匹配的订单id
        $filter = [];
        $orderGoods=new orderGoodsModel();
        $orderInfo=$orderGoods->getorderGoodsByName(['goods_name' => ['like','%'.$goods_name.'%'],'user_id'=>$user_id]);
        if($orderInfo){
            $a=[];
            foreach ($orderInfo->toArray() as $k=>$v){
                $a[]=$v['order_id'];
            }
            $filter['order_id']=['in',$a];
        }
        // 筛选条件
        // 订单数据类型
        switch ($type) {
            case 'all':
                break;
            case 'payment';
                $filter['pay_status'] = PayStatusEnum::PENDING;
                $filter['order_status'] = 10;
                break;
            case 'delivery';
                $filter['pay_status'] = PayStatusEnum::SUCCESS;
                $filter['delivery_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'received';
                $filter['pay_status'] = PayStatusEnum::SUCCESS;
                $filter['delivery_status'] = 20;
                $filter['receipt_status'] = 10;
                $filter['order_status'] = 10;
                break;
            case 'comment';
                $filter['is_comment'] = 0;
                $filter['order_status'] = 30;
                break;
        }
        return $this->with(['goods.image'])
            ->where('user_id', '=', $user_id)
            ->where($filter)
            ->where('is_delete', '=', 0)
            ->where(['order_source'=>['IN',[10,20,30]]])
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 取消订单
     * @param UserModel $user
     * @return bool|mixed
     */
    public function cancel($user){
        if ($this['delivery_status']['value'] == 20) {
            $this->error = '已发货订单不可取消';
            return false;
        }
        // 订单取消事件
        return $this->transaction(function () use ($user) {
            // 订单是否已支付
            $isPay = $this['pay_status']['value'] == PayStatusEnum::SUCCESS;
            // 未付款的订单
            $describe = "订单取消：{$this['order_no']}";
            if ($isPay == false) {
                // 回退商品库存
                FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], $isPay);
                // 回退用户优惠券
                $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
                // 回退用户积分
                $this['points_num'] > 0 && $user->setIncPoints($this['points_num'], $describe);
                // 回退用户零钱
                $this['balance_num'] > 0 && $user->setIncBalance($this['balance_num'], $describe,40);
                // 更新订单状态
                return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' => $isPay ? OrderStatusEnum::APPLY_CANCEL : OrderStatusEnum::CANCELLED]);
            }else{
                //余额支付
                if($this['pay_type']['value']==10){
                    //储蓄余额
                    if($this['pay_way']==10){
                        if($this['delivery_status']['value']==10){
                            //未发货
                            //更新储蓄余额流水
                            $userMoneyData=[
                                'user_id'=>$user['user_id'],
                                'scene'=>20,
                                'money'=>$this['total_price'],
                                'describe'=>'用户取消订单',
                                'remark'=>'用户取消订单',
                                'order_no'=>$this['order_no'],
                                'wxapp_id'=>$this['wxapp_id'],
                                'create_time'=>time()
                            ];
                            Db::name('user_money_log')->insert($userMoneyData);
                            //更新储蓄总金额
                            Db::name('user')->where(['user_id'=>$user['user_id']])->setInc('money',$this['total_price']);
                            // 更新订单状态
                            return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' =>20]);
                        }else{
                            //已发货
                            // 更新订单状态
                            return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' =>21]);
                        }
                    }else{
                        if($this['delivery_status']['value']==10){
                            //未发货
                            //收益余额
                            //更新收益余额流水
                            $delerMoneyData=[
                                'user_id'=>$user['user_id'],
                                'flow_type'=>80,
                                'money'=>$this['total_price'],
                                'describe'=>'用户取消订单',
                                'wxapp_id'=>$this['wxapp_id'],
                                'create_time'=>time(),
                                'update_time'=>0
                            ];
                            Db::name('dealer_capital')->insert($delerMoneyData);
                            //更新收益总金额
                            Db::name('dealer_user')->where(['user_id'=>$user['user_id']])->setInc('money',$this['total_price']);
                            // 更新订单状态
                            return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' =>20]);
                        }else{
                            //已发货
                            // 更新订单状态
                            return $this->isUpdate(true)->save(['order_id'=>$this['order_id'],'order_status' =>21]);
                        }
                    }
                    // 回退商品库存
                    FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], $isPay);
                    //回退用户优惠券
                    $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
                }
            }
            //取消订单，改变分账状态
        });
    }
    /**
     * 余额支付
     * @param $user
     * @param $order
     * @param $password
     * @param $payWay
     * @return bool
     * @throws BaseException
     * @throws \think\exception\DbException
     **/

    public function onOrderPaymentByBalance($user,$order,$password,$balanceType)
    {
        $result=PaymentService::balance($user,$order,$password,$balanceType);
        if($result){
            return $this->onPaymentByBalance($order['order_no']);
        }else{
            throw new BaseException(['msg' => '支付错误，请稍后重新支付']);
        }
    }
    /**
     * 获取订单总数
     * @param $user
     * @param string $type
     * @return int|string
     * @throws \think\Exception
     */
    public function getCount($user, $type = 'all')
    {

        if ($user === false) {
            return false;
        }
        // 筛选条件
        $filter = [];
        // 订单数据类型
        switch ($type) {
            case 'all':
                break;
            case 'daifukuan';//待付款
                $filter['pay_status'] = PayStatusEnum::PENDING;
                break;
            case 'daifahuo';//待发货
                $filter['pay_status'] = PayStatusEnum::SUCCESS;
                $filter['delivery_status'] = 10;
                $filter['receipt_status'] = 10;
                break;
            case 'daishouhuo';//待收货
                $filter['order_status'] = 10;
                $filter['delivery_status'] = 20;
                $filter['receipt_status'] = 10;
                $filter['is_comment'] = 0;
                break;
            case 'daipingjia';//待评价
                $filter['order_status'] = 30;
                $filter['delivery_status'] = 20;
                $filter['receipt_status'] = 20;
                $filter['is_comment'] = 0;
                break;
            case 'daishouhou';//待售后
                $filter['order_status'] = 21;//21:已申请待审核
                break;
        }
        return $this->where('user_id', '=', $user['user_id'])
            ->where('order_status', '<>', 20)
            ->where(['order_source'=>['NOT IN',[40,50]]])
            ->where($filter)
            ->where('is_delete', '=', 0)
            ->count();
    }
    /**
     * 余额支付标记订单已支付
     * @param $orderNo
     * @param $payWay //余额支付方式
     * @return bool
     * @throws \think\exception\DbException
     */
    public function onPaymentByBalance($orderNo)
    {

        // 获取订单详情
        $PaySuccess = new PaySuccess($orderNo);
        // 发起余额支付
        $status = $PaySuccess->onPaySuccess(PayTypeEnum::BALANCE);
        if (!$status) {
            $this->error = $PaySuccess->getError();
            return false;
        }
        return $status;
    }
    /*
     * 获取待售后的订单总数
     */
    public function getShouHouCount($user){
        return Db::name('order_refund')->where(['user_id'=>$user['user_id'],'wxapp_id'=>$user['wxapp_id'],'status'=>0])->count();
    }
}
